package com.bonc.ioc.demo.utils;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bonc.ioc.demo.exception.McpException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * @program: bonc_ycfnxf_bpm
 * @description: Http请求工具类
 * @author: ycy
 * @create: 2019-03-29 10:51
 */
@Slf4j
public class HttpUtil {

    /**
     * @Description: http post请求
     * @Author: yxy
     * @Date: 2019/2/25 9:55
     * @param: url：请求路径；param：请求参数；
     * @throws:
     * @return:
     */
    public static String post(String url, Map<String, String> header, Map<String, Object> param) {
        try {
            JSONObject jsonObject = new JSONObject(param);
            //创建连接对象
            HttpClient client = new HttpClient();
            //创建请求
            PostMethod method = new PostMethod(url);
            //设置请求头格式为json格式
            RequestEntity entity = new StringRequestEntity(jsonObject.toString(), "application/json", "UTF-8");
            //设置请求体信息
            method.setRequestEntity(entity);
            //往heard里放入参数
            if (header != null) {
                Set headerKeys = header.keySet();
                Iterator iterator = headerKeys.iterator();
                while (iterator.hasNext()) {
                    String key = iterator.next().toString();
                    String value = header.get(key);
                    if (key != null && !"".equals(key) && value != null && !"".equals(value)) {
                        method.addRequestHeader(key, value);
                    }
                }
            }

            //创建连接
            client.executeMethod(method);
            //获取返回信息
            InputStream in = method.getResponseBodyAsStream();
            InputStreamReader isr = new InputStreamReader(in, "UTF-8");
            char[] b = new char[1024];
            StringBuffer result = new StringBuffer();
            for (int n; (n = isr.read(b)) != -1; ) {
                result.append(new String(b, 0, n));
            }
            return result.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * @Description: http get请求
     * @Author: yxy
     * @Date: 2019/5/20 9:44
     * @param: url：请求路径；param：请求参数；
     * @throws:
     * @return:
     */
    public static String get(String url, Map<String, String> header, Map<String, String> param) {
        try {
            StringBuffer buffer = new StringBuffer();
            buffer.append(url);
            //拼接参数
            if (param != null) {
                Set paramKeys = param.keySet();
                Iterator iterator = paramKeys.iterator();
                boolean isFirst = true;
                while (iterator.hasNext()) {
                    if (isFirst) {
                        buffer.append("?");
                    } else {
                        buffer.append("&");
                    }
                    isFirst = false;
                    String key = iterator.next().toString();
                    buffer.append(key).append("=").append(param.get(key));
                }

            }
            CloseableHttpClient client = HttpClients.createDefault();
            //创建连接对象
            log.info("url = {}" ,buffer.toString());
            HttpGet httpGet = new HttpGet(buffer.toString());
            //往heard里放入参数
            if (header != null) {
                Set headerKeys = header.keySet();
                Iterator iterator = headerKeys.iterator();
                while (iterator.hasNext()) {
                    String key = iterator.next().toString();
                    String value = header.get(key);
                    if (key != null && !"".equals(key) && value != null && !"".equals(value)) {
                        httpGet.addHeader(key, value);
                    }
                }
            }
            //创建请求
            HttpResponse httpResponse = client.execute(httpGet);
            return EntityUtils.toString(httpResponse.getEntity());
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    // 获取数据治理平台http请求结果
    public static String sendDataDealRequest(Map<String, Object> objectInfo, String url,
                                             Long token, String serviceName) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("token", token);
        paramMap.put("objectInfo", objectInfo);
        String result = HttpUtil.post(url, null, paramMap);
        if (StringUtils.isEmpty(result)) {
            throw new McpException("请求" + serviceName + "服务失败！");
        }
        JSONObject resultJson = JSONObject.parseObject(result);
        if (!"200".equals(resultJson.getString("returnStatus"))) {
            throw new McpException("获取" + serviceName + "失败！");
        }
        return resultJson.getString("returnInfo");
    }

    // 获取数据治理平台http请求结果
    public static JSONObject getDataDealRequestResult(Map<String, Object> objectInfo, String url,
                                                      Long token, String serviceName) {
        String returnInfo = sendDataDealRequest(objectInfo, url, token, serviceName);
        return JSONObject.parseObject(returnInfo);
    }
    
    // 获取数据治理平台http请求结果
    public static JSONArray getDataDealRequestResultArray(Map<String, Object> objectInfo, String url,
                                                          Long token, String serviceName) {
        String returnInfo = sendDataDealRequest(objectInfo, url, token, serviceName);
        return JSONArray.parseArray(returnInfo);
    }
}
